﻿

function getDomainFromUrl(url) {
  var host = "null";
  if (typeof url == "undefined" || null == url)
    url = window.location.href;
  var regex = /.*\:\/\/([^\/]*).*/;
  var match = url.match(regex);
  if (typeof match != "undefined" && null != match)
    host = match[1];
  return host;
}

function checkForValidUrl(tabId,changeInfo,tab) {
  if (getDomainFromUrl(tab.url).toLowerCase() == "www.cnblogs.com") {
    chrome.pageAction.show(tabId);
  }
};


function getCookie(name) {
  var cookieValue = null;
  if (document.cookie && document.cookie !== '') {
    var cookies = document.cookie.split(';');
    for (var i = 0;i < cookies.length;i++) {
      var cookie = jQuery.trim(cookies[i]);
      // Does this cookie string begin with the name we want?
      if (cookie.substring(0,name.length + 1) === (name + '=')) {
        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
        break;
      }
    }
  }
  return cookieValue;
}


get = function(url,success,error) {
  //1创建一个xhr对象
  var xhr = new XMLHttpRequest();
  //2监听状态的改变
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {//请求成功
      if (xhr.status === 200) {//响应成功
        success(xhr.responseText);//调用一个函数
      }
    } else {
      error()
    }
  }
  //3打开一个链接
  xhr.open('get',url,true);
  //1.请求方式  2.发送到哪去  3.是否为异步请求 是true 否 flase
  //4发送数据
  xhr.send(null);
}

post = function(url,param,success,error) {
  //创建一个xhr对象
  var xhr = new XMLHttpRequest();
  //监听状态的改变
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {//请求成功
      if (xhr.status === 200) {//响应成功
        success(xhr.responseText);//调用一个函数
      }
    } else {
      error()
    }
  }
  //打开一个链接
  xhr.open('post',url,false);
  //修改请求消息头部
  xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
  xhr.setRequestHeader("X-CSRFToken",getCookie("csrftoken"))

  //发送数据
  xhr.send(param);
}

// post("http://dbadmin.haiziwang.com/instance/getUserdbNameList/", "instance_name=1", function (data) {
//   console.log(data)
// }, function () {
//   console.log("error")
// })


$(function() {
  $.ajaxSetup({
    headers: {"X-CSRFToken": getCookie("csrftoken")}
  });
});
$(document).ready(function() {


  chrome.runtime.onMessage.addListener(function(request,sender,sendResponse) {
    if ("init" == request.action) {
      sendResponse({
        instance_name_html: $('#instance_name').html()
      });
    } else if ("getInstanceNameList" == request.action) {
      sendResponse($('#instance_name').html())
    }
    else if ("getDbNameList" == request.action) {

      $.ajax({
        type: "post",
        url: "http://dbadmin.haiziwang.com/instance/getUserdbNameList/",
        dataType: "json",
        data: request.data,
        async: false,
        complete: function() {
          sendResponse({"callType": "complete"})
        },
        success: function(data) {
          sendResponse({"callType": "success","data": data})
        },
        error: function(XMLHttpRequest,textStatus,errorThrown) {
          sendResponse({"callType": "error","data": errorThrown})
        }
      });
    } else if ("getTableNameList" == request.action) {

      $.ajax({
        type: "post",
        url: "http://dbadmin.haiziwang.com/instance/getTableNameList/",
        dataType: "json",
        data: request.data,
        async: false,
        complete: function() {
          sendResponse({"callType": "complete"})
        },
        success: function(data) {
          sendResponse({"callType": "success","data": data})
        },
        error: function(XMLHttpRequest,textStatus,errorThrown) {
          sendResponse({"callType": "error","data": errorThrown})
        }
      });
    }
  });

  //获取数据库实例
  chrome.runtime.sendMessage({
    action: 'init_instance_name',
    data: $('#instance_name').html(),
  },
    function(response) {
      console.log(response.farewell);
    }
  );

  chrome.runtime.sendMessage({
    action: 'init_page_cookie',
    data: document.URL,
  },
    function(response) {
      console.log(response.farewell);
    }
  );

});
